/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.lcm.metadata.rtservice;

import com.google.common.collect.Lists;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.Metadata4Ref;
import com.inspur.edp.lcm.metadata.api.entity.MetadataCustomizationFilter;
import com.inspur.edp.lcm.metadata.api.entity.MetadataIndexItemDto;
import com.inspur.edp.lcm.metadata.api.entity.MetadataProject;
import com.inspur.edp.lcm.metadata.api.entity.MetadataRTFilter;
import com.inspur.edp.lcm.metadata.api.entity.ProcessMode;
import com.inspur.edp.lcm.metadata.api.entity.ServiceUnitInfo;
import com.inspur.edp.lcm.metadata.api.service.MetadataRTService;
import com.inspur.edp.lcm.metadata.common.util.ClassifierUtils;
import com.inspur.edp.metadata.rtcustomization.api.CustomizationService;
import com.inspur.edp.metadata.rtcustomization.api.entity.Metadata4RefQueryParam;
import com.inspur.edp.metadata.rtcustomization.api.entity.MetadataFilter;
import com.inspur.edp.metadata.rtcustomization.api.entity.MetadataQueryParam;
import com.inspur.edp.metadata.rtcustomization.api.entity.MetadataScopeEnum;
import com.inspur.edp.metadata.rtcustomization.api.entity.SourceTypeEnum;
import com.inspur.edp.metadata.rtcustomization.serverapi.CustomizationRtServerService;
import io.iec.edp.caf.commons.utils.CollectionUtils;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MetadataRTServiceImp implements MetadataRTService {
    private final CustomizationService customizationService;

    private final CustomizationRtServerService customizationRtServerService;

    public MetadataRTServiceImp() {
        customizationService = SpringBeanUtils.getBean(CustomizationService.class);
        customizationRtServerService = SpringBeanUtils.getBean(CustomizationRtServerService.class);
    }

    @Override
    public GspMetadata getMetadataRTByID(String id) {
        MetadataQueryParam metadataQueryParam = new MetadataQueryParam();
        metadataQueryParam.setMetadataId(id);
        // 根据需要传入即可，默认是国际化
        metadataQueryParam.setIsI18n(false);
        metadataQueryParam.setMetadataScopeEnum(MetadataScopeEnum.RUNTIME);
        return customizationService.getGspMetadata(metadataQueryParam);

    }

    @Override
    public GspMetadata getMetadata(String id) {
        MetadataQueryParam metadataQueryParam = new MetadataQueryParam();
        // 传入需要查询的元数据id信息
        metadataQueryParam.setMetadataId(id);
        metadataQueryParam.setIsI18n(true);
        metadataQueryParam.setMetadataScopeEnum(MetadataScopeEnum.RUNTIME);
        return customizationService.getGspMetadata(metadataQueryParam);
    }

    @Override
    public GspMetadata getMetadata(MetadataCustomizationFilter metadataCustomizationFilter) {
        MetadataQueryParam metadataQueryParam = new MetadataQueryParam();
        // 传入需要查询的元数据id信息
        metadataQueryParam.setMetadataId(metadataCustomizationFilter.getMetadataId());
        // 根据需要传入即可，默认是国际化
        metadataQueryParam.setIsI18n(metadataCustomizationFilter.getIsI18n());
        metadataQueryParam.setMetadataScopeEnum(MetadataScopeEnum.RUNTIME);
        return customizationService.getGspMetadata(metadataQueryParam);

    }

    @Override
    public List<Metadata4Ref> getMetadataRefList(String metadataTypes) {
        List<String> typeList;
        if (metadataTypes == null || metadataTypes.isEmpty()) {
            throw new RuntimeException("传入参数不能为空");
        } else {
            String[] types = metadataTypes.split(",");
            typeList = new ArrayList<>(Arrays.asList(types));
        }
        MetadataFilter metadataFilter = new MetadataFilter();
        metadataFilter.setMetadataTypes(typeList);
        return customizationRtServerService.getMetadataListByFilter(metadataFilter);

    }

    @Override
    public List<Metadata4Ref> getMetadataRefList() {
        return customizationRtServerService.getMetadataListByFilter(new MetadataFilter(SourceTypeEnum.MDPKG, null));
    }

    @Override
    public List<Metadata4Ref> getMetadataListByFilter(MetadataRTFilter filter) {
        // 获取所有元数据包
        List<Metadata4Ref> metadataList = getMetadataRefList();
        // 根据AppCode进行过滤
        if (filter.getAppCode() != null) {
            metadataList = metadataList.stream().filter(item -> item.getServiceUnitInfo() == null || filter.getAppCode().equalsIgnoreCase(item.getServiceUnitInfo().getAppCode())).collect(Collectors.toList());
        }
        // 根据ServiceUnitCode进行过滤
        if (filter.getServiceUnitCode() != null) {
            metadataList = metadataList.stream().filter(item -> item.getServiceUnitInfo() == null || filter.getServiceUnitCode().equalsIgnoreCase(item.getServiceUnitInfo().getServiceUnitCode())).collect(Collectors.toList());
        }
        // 根据BizobjectID进行过滤
        if (filter.getBizobjectId() != null && filter.getBizobjectId().size() > 0) {
            for (String eachBizobjectId : filter.getBizobjectId()) {
                metadataList = metadataList.stream().filter(item -> eachBizobjectId.equals(item.getMetadata().getHeader().getBizobjectID())).collect(Collectors.toList());
            }
        }
        if (filter.getCode() != null) {
            metadataList = metadataList.stream().filter(item -> item.getMetadata().getHeader().getCode() != null && item.getMetadata().getHeader().getCode().equals(filter.getCode())).collect(Collectors.toList());
        }
        if (filter.getNameSpace() != null) {
            metadataList = metadataList.stream().filter(item -> item.getMetadata().getHeader().getNameSpace() != null && item.getMetadata().getHeader().getNameSpace().equals(filter.getNameSpace())).collect(Collectors.toList());
        }
        if (filter.getType() != null) {
            metadataList = metadataList.stream().filter(item -> item.getMetadata().getHeader().getType() != null && item.getMetadata().getHeader().getType().equals(filter.getType())).collect(Collectors.toList());
        }

        return metadataList;
    }

    @Override
    public GspMetadata getMetadataBySemanticID(String metadataNamespace, String metadataCode, String metadataTypeCode) {

        if(Objects.isNull(metadataNamespace) || Objects.isNull(metadataCode) || Objects.isNull(metadataTypeCode)){
            return null;
        }
        MetadataFilter metadataFilter = new MetadataFilter();
        metadataFilter.setMetadataNamespace(metadataNamespace);
        metadataFilter.setMetadataCode(metadataCode);
        metadataFilter.setMetadataTypes(Lists.newArrayList(metadataTypeCode));
        List<Metadata4Ref> metadata4RefList = customizationRtServerService.getMetadataListByFilter(metadataFilter);

        if(org.springframework.util.CollectionUtils.isEmpty(metadata4RefList)){
            return null;
        }

        return metadata4RefList.get(0).getMetadata();
    }

    @Override
    public ServiceUnitInfo getServiceUnitInfo(String metadataId) {
        return customizationRtServerService.getServiceUnitInfo(metadataId);
    }

    @Override
    public Metadata4Ref getMetadata4Ref(String metadataId) {
        return customizationRtServerService.getMetadata4Ref(metadataId);
    }

    public List<MetadataIndexItemDto> getDBMetadataList(String text, String absolutePath, List<String> typeList, boolean page, int pageSize, int pageIndex, MetadataProject metadataProject) {
        // 获取元数据
        List<Metadata4Ref> metadata4RefList = getMetadata4RefListByTypeList(typeList, metadataProject);
        List<MetadataIndexItemDto> metadataIndexItemDtoList = new ArrayList<>();
        if (CollectionUtils.isEmpty(metadata4RefList)) {
            return metadataIndexItemDtoList;
        }
        // 按关键字过滤及分页处理
        String packageNameExcluded = metadataProject.getMetadataPackageInfo().getName();
        if (!page) {
            for (Metadata4Ref metadata4Ref : metadata4RefList) {
                if (isValidMd(metadata4Ref, text, packageNameExcluded)) {
                    metadataIndexItemDtoList.add(new MetadataIndexItemDto(metadata4Ref));
                }
            }
        } else {
            int count = 0;
            int skip = pageIndex * pageSize;
            int max = pageSize + skip;
            for (Metadata4Ref metadata4Ref : metadata4RefList) {
                if (count >= max) {
                    break;
                }
                if (isValidMd(metadata4Ref, text, packageNameExcluded)) {
                    count++;
                    if (count <= skip) {
                        continue;
                    }
                    metadataIndexItemDtoList.add(new MetadataIndexItemDto(metadata4Ref));
                }
            }
        }
        return metadataIndexItemDtoList;
    }
    @Override
    public List<Metadata4Ref> getMetadata4RefListByTypeList( List<String> typeList, MetadataProject metadataProject) {
        if (Objects.isNull(metadataProject)) {
            return new ArrayList<>();
        }
        // 不支持生成型引用运行时
        if (ProcessMode.generation == metadataProject.getMetadataPackageInfo().getProcessMode()) {
            return new ArrayList<>();
        }
        // 查询mdpkg和idp数据
        Metadata4RefQueryParam metadata4RefQueryParam = new Metadata4RefQueryParam();
        metadata4RefQueryParam.setMetadataScopeEnum(MetadataScopeEnum.RUNTIME);
        metadata4RefQueryParam.setSourceTypeEnumList(Lists.newArrayList(SourceTypeEnum.MDPKG, SourceTypeEnum.GENERATED));
        metadata4RefQueryParam.setMetadataTypeList(typeList);
        List<Metadata4Ref> metadata4RefList = customizationService.getMetadataList(metadata4RefQueryParam);
        if(Objects.isNull(metadata4RefList)) {
            metadata4RefList = new ArrayList<>();
        }
        return metadata4RefList;
    }
    @Override
    public Metadata4Ref getMetadata4RefById(String metadataId) {
        CustomizationRtServerService customizationRtServerService = SpringBeanUtils.getBean(CustomizationRtServerService.class);
        return customizationRtServerService.getMetadata4RefById(metadataId);
    }

    /**
     * 检查是否符合查询条件
     *
     * @param metadata4Ref
     * @param text
     * @param packageNameExcluded
     * @return
     */
    private boolean isValidMd(Metadata4Ref metadata4Ref, String text, String packageNameExcluded) {
        // 排除自己
        if( Objects.nonNull(metadata4Ref) &&
                Objects.nonNull(metadata4Ref.getPackageHeader()) &&
                Objects.nonNull(metadata4Ref.getPackageHeader().getName()) &&
                metadata4Ref.getPackageHeader().getName().equals(packageNameExcluded)){
            return false;
        }
        if(Objects.isNull(text) || text.isEmpty()){
            return true;
        }
        if (isMath(metadata4Ref.getMetadata().getHeader().getCode(), text)) {
            return true;
        }
        if (isMath(metadata4Ref.getMetadata().getHeader().getName(), text)) {
            return true;
        }
        if (Objects.nonNull(metadata4Ref.getPackageHeader()) && isMath(metadata4Ref.getPackageHeader().getName(), text)) {
            return true;
        }
        return false;
    }

    private boolean isMath(String content, String text) {
        if (Objects.isNull(content) || content.isEmpty()) {
            return false;
        }
        return content.toLowerCase().contains(text.toLowerCase());
    }

}
